import { defineStore } from 'pinia';
import Layout from "@/components/Layout";
import Router from "@/router";
import { getMenus } from "@/api/login";
import { appId } from "@/utils/constants";
import { getUserId } from "@/utils/auth";
import { resss, router } from "@/utils/config";

const home = {
  path: "/",
  name: "home",
  component: "Layout",
  redirect: '/',
  meta: {
    icon: "category",
    title: '首页',
    breadcrumb: false
  },
  children: [
    {
      name: "home",
      path: "/",
      component: "home/index",
      meta: {
        icon: "category",
        title: '首页'
      }
    }
  ]
};
const views: Record<string, any> = import.meta.glob(["/src/views/**/*.vue",]);

// pinia状态管理器
export default defineStore('routes', {
  state: () => {
    return {
      // 路由表
      routes: [] as Array<any>,
      permissions: ['user:role:add', 'user:role:edit']
    }
  },
  getters: {},
  actions: {
    // 添加动态路由，并同步到状态管理器中
    SET_MENU_ROUTE() {
      return new Promise(resolve => {
        if (this.routes.length <= 0) {

          getMenus({
            userId: "",
            token: "",
            version: "",
            data: {
              appId,
              globalUserId: getUserId()
            }
          }).then((res: any) => {

            let list = getMenuList([], res);
            let rou = filterAsync(router, list);
            rou.unshift(home);
            const sidebarRoutes = filterAsyncRouter(rou);
            sidebarRoutes.forEach(route => {
              Router.addRoute(route);
            });
            this.routes = sidebarRoutes;
            resolve(true);
          });
          
        } else {
          resolve(false);
        }
      })
    },
  }
})


// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap: Object[]) {
  return asyncRouterMap.filter((route: any) => {
    if (route.component) {
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = views[`/src/views/${route.component}`];
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterChildren(route.children)
    } else {
      delete route['children'];
      delete route['redirect'];
    }
    return true
  })
}

function filterChildren(childrenMap: any[]) {
  var children: any = [];
  childrenMap.forEach((el) => {
    el.component = views[`/src/views/${el.component}.vue`];
    children = children.concat(el);
  })
  return children
}

function getMenuList(list: any, data: any) {
  for (const key in data) {
    list.push(data[key]['menusCode']);
    if (data[key]['structureMenusChildList']) {
      list.concat(getMenuList(list, data[key]['structureMenusChildList']));
    }
  }
  return list;
}

function hasPermission(permission: any, route: any) {
  if (route.meta && route.meta.permission) {
    let flag = false
    for (let i = 0, len = permission.length; i < len; i++) {
      flag = route.meta.permission.includes(permission[i]);
      if (flag) {
        return true
      }
    }
    return false
  }
  return true
}

function filterAsync(routerMap: any, menuList: any) {
  const accessedRouters = routerMap.filter((route: any) => {
    if (hasPermission(menuList, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsync(route.children, menuList)
      }
      return true
    }
    return false
  })
  return accessedRouters
}